package com.example.android10_client;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.os.Build;
import android.os.StrictMode;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {

	InputStream is;
	OutputStream os;
	Socket socket;
	ObjectInputStream ois;
	ObjectOutputStream oos;
	TextView tv;
	EditText et;
	Button bt;
	String rMsg;

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);

		setContentView(R.layout.activity_main);

		tv = (TextView) findViewById(R.id.retMsg);
		et = (EditText) findViewById(R.id.sendMsg);
		bt = (Button) findViewById(R.id.send);
		bt.setOnClickListener(this);
		rMsg ="";
	}
    
	@Override
	public void onClick(View v) {

		start();
		tv.setText(rMsg);
	}

	public void start() {
		try {
			socket = new Socket("211.183.2.174", 5000);
			sendMessage(socket);
			receiveMessage(socket);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		finally{
			try{
				socket.close();
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	private void receiveMessage(Socket socket2) {
		try {
			is = socket2.getInputStream();
			ois = new ObjectInputStream(is);
			 
				rMsg += (String) ois.readObject();
				rMsg += "\n";
			 
			
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private void sendMessage(Socket socket2) {
		try {
			os = socket2.getOutputStream();
			oos = new ObjectOutputStream(os);
			String sMsg = et.getText().toString();
			oos.writeObject(sMsg);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
